<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class News_model extends MY_Model {

    protected $news;
    protected $categories_news;

    function __construct(){
        parent::__construct();
    }

    function table_name(){
        return "news";
    }

    function get_news($filters = array(),$counting = false){
        if (isset($this->CI->cache)){
            $caching = true;
            $cache_key = 'ci--NEWS_'.md5(serialize($filters));
            if ($counting){
                $cache_key = 'ci--NEWS_COUNT_'.md5(serialize($filters));
            }
            if ($return = $this->cache->file->get($cache_key)) {
                return ($return == 'empty_cache') ? FALSE : $return;
            }
        }else{
            $caching = false;
        }

        $sql = "SELECT `news`.*, `cn`.`category_id` as category_id, `cc`.`name` as category_name, `cc`.`alias` AS category_alias
                FROM (`news`) LEFT JOIN `categories_news` as cn ON `cn`.`new_id` = `news`.`new_id`
                LEFT JOIN `categories` as cc ON `cc`.`category_id` = `cn`.`category_id` WHERE 1=1 ";
        $param = array();
        if (isset($filters['new_id'])){
            $sql .= ' AND news.new_id = ?';
            $param[] = $filters['new_id'];
        }

        if (isset($filters['name'])){
            $sql .= " AND news.name like ?";
            $param[] = '%' .$filters['name'] . '%';
        }

        if (isset($filters['category_id'])){
            $sql .= ' AND (cc.category_id =? OR cc.parent_id =?)';
            $param[] = $filters['category_id'];
            $param[] = $filters['category_id'];
        }

        if (isset($filters['new_category'])){
            $sql .= ' AND cc.category_id = ?';
            $param[] = $filters['new_category'];
        }

        if (isset($filters['status'])){
            $sql .= ' AND news.status = ?';
            $param[] = $filters['status'];
        }

        if (isset($filters['featured'])){
            $sql .= ' AND news.featured = ?';
            $param[] = $filters['featured'];
        }

        if (isset($filters['is_hot'])){
            $sql .= ' AND news.is_hot = ?';
            $param[] = $filters['is_hot'];
        }

        if (isset($filters['other_new_id'])){
            $sql .= ' AND news.new_id != ?';
            $param[] = $filters['other_new_id'];
        }

        if (isset($filters['alias'])){
            $sql .= ' AND news.alias = ?';
            $param[] = $filters['alias'];
        }
        $sql .= " ORDER BY `news`.`new_id` DESC";
        if (isset($filters['limit'])) {
            $offset = (isset($filters['page'])) ? $filters['page'] : 0;
            $sql .= ' LIMIT ?, ?';
            $param[] = (int)$offset;
            $param[] = (int)$filters['limit'];

        }

        $result = $this->db->query($sql, $param);

        if($counting !=false){
            $rows = $result->num_rows();
            $result->free_result();

            if ($caching == TRUE) {
                $this->CI->cache->file->save($cache_key, $rows, (5*60));
            }

            return $rows;
        }
        if ($result->num_rows() == 0) {
            return false;
        }
        $news = array();
        foreach ($result->result_array() as $row ){
            $row['link'] = create_url('tin-tuc/'.$row['category_alias'].'/'.$row['alias'],array('rewrite'=>true));
            $row['date'] = fdate($row['created'],"%A, %d/%m/%Y - %H:%M");
            $news[] = $row;
        }
        if ($caching){
            $this->CI->cache->file->save($cache_key,$news);
        }
        $result->free_result();

        return $news;
    }

    function get_categories_options($filters=array()){
        $categories_options = array();
        $categories = $this->get_categories($filters);
        if (is_array($categories) && count($categories)){
            foreach ($categories as $category){
                $categories_options[$category['category_id']] = $category['name'];
            }
        }
        return $categories_options;
    }

    function get_categories($filters = array(),$counting = false,$treerecurse = true){
        $this->CI->load->model('categories/categories_model');
        $filters = array_merge(array('module'=>'news'),$filters);
        $cactegory_news = $this->categories_model->get_categories($filters,$counting);
        if ($counting){
            return $cactegory_news;
        }
        if ($treerecurse){
            $list_categories = array();
            if (is_array($cactegory_news) && count($cactegory_news)> 0){
                $children = array();
                foreach ($cactegory_news as $v){
                    $v['id'] = $v['category_id'];
                    $pt = $v['parent_id'];
                    $list = @$children[$pt] ? $children[$pt] : array();
                    array_push( $list, $v );
                    $children[$pt] = $list;
                }
                $list_categories = treerecurse(0,'-',array(), $children,99999);
            }
            return $list_categories;
        }else{
            if ($cactegory_news){
                return $cactegory_news;
            }
        }
        return false;
    }

    function get_count_categories($filters = array()) {
        return $this->get_categories($filters,true);
    }

    function get_count($filter = array()){
        return $this->get_news($filter,true);
    }

    function get_new($newId){
        if (!isset($this->news[$newId])){
            $new = $this->get_news(array('new_id'=>$newId));
            $this->news[$newId] = $new;
        }else{
            $new = $this->news[$newId];
        }
        if (empty($new)) {
            return false;
        }
        return $new[0];
    }

    function insert_new($data){
        $_category_id = $data['category_id'];
        $_new_id = $this->save($data);
        if ($_category_id) {
            $this->save(array('category_id' => $_category_id, 'new_id' => $_new_id, 'position' => 1), 'categories_news');
        }
        return true;
    }

    function update_new($data,$new_id){
        $attributes = $this->delete_image_file($new_id, $data);

        $this->delete(array('new_id' => $new_id), 'categories_news');
        $_category_id = $data['category_id'];
        if ($_category_id) {
            $this->save(array('category_id' => $_category_id, 'new_id' => $new_id, 'position' => 1), 'categories_news');
        }
        return $this->update($attributes, array('new_id' => $new_id));
    }

    function delete_image_file($new_id, $data = false, $is_delete = false){
        $files = $this->db->select('image')->from('news')->where('new_id',$new_id)->get()->result_array();
        foreach ($files[0] as $k=>$v){
            if (is_array($data) && count($data) > 0 && array_key_exists($k.'_delete',$data)){
                if (file_exists($v)){
                    unlink($v);
                }
                $data[$k]="";
            }else if ($is_delete){
                if (file_exists($v)){
                    unlink($v);
                }
            }
        }
        return $data;
    }

    function delete_new($new_id) {
        $this->delete_image_file($new_id);
        $this->delete(array('new_id'=>$new_id),'categories_news');
        return $this->delete(array('new_id'=>$new_id));
    }

    function change_status_news($new_id) {
        $status = $this->db->select('status')->from('news')->where('new_id', $new_id)->get()->result_array();

        if ($status[0]['status'] == 1) {
            $change = 0;
        } else {
            $change = 1;
        }
        return $this->update(array('status' => $change), array('new_id' => $new_id));
    }

    function insert_category_new($categoryId,$newsId){
        $fields = array('category_id'=>$categoryId,'new_id'=>$newsId);
        $this->db->insert('categories_news',$fields);
    }

    function delete_category($category_id){
        $this->db->where('category_id',$category_id);
        $this->db->delete('categories_news');
        $this->load->model('categories/categories_model');
        $this->categories_model->delete_category($category_id);
        if (isset($this->CI->cache)) {
            $this->CI->cache->file->clean();
        }
        return true;
    }

    function get_new_by_alias($new_alias){
        $new = $this->get_news(array('alias'=>$new_alias),false);
        if ($new){
            return $new[0];
        }
        return false;
    }
    
}
?>